<template>
  <div>
    <myDivider name="角色管理"></myDivider>
    <div style="margin-left: 20px">
      <el-input maxlength="20" style="width: 150px" v-model="query.roleName" placeholder="角色名称"
        @keyup.enter.native="getTableList" clearable></el-input>
      <el-select style="width: 150px" @change="SouSuo" v-model="query.roleType" placeholder="请选择角色类型">
        <div v-if="logOnUser.unitType == 'system'">
          <el-option label="所有" value=""></el-option>
          <el-option label="系统管理员" value="system"></el-option>
          <el-option label="机关管理员" value="agency"></el-option>
          <el-option label="机构管理员" value="company"></el-option>

        </div>
        <div v-if="logOnUser.unitType == 'agency'">
          <el-option label="机关管理员" value="agency"></el-option>
        </div>
        <div v-if="logOnUser.unitType == 'company'">
          <el-option label="机构管理员" value="company"></el-option>
        </div>
      </el-select>
      <el-select style="width: 150px" @change="SouSuo" v-model="query.isSuperAdmin" placeholder="筛选管理员身份">
        <el-option label="所有管理员" value="2"></el-option>
        <el-option label="普通管理员" value="0"></el-option>
        <el-option label="超级管理员" value="1"></el-option>
      </el-select>
      <el-button type="primary" style=" margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style=" margin-left: 15px" @click="reset">重置</el-button>
      <div style="margin-top: 10px;">
        <el-button type="primary" @click="openForm">新增</el-button>
      </div>
    </div>
    <div class="popTableStyle">
      <el-table :data="roleData" style="width: 100%;margin-top: 100px;" row-key="uid"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">


        <el-table-column align="center" prop="name" label="角色名称">
        </el-table-column>
        <el-table-column align="center" prop="unitTypeName" label="角色类型">
        </el-table-column>
        <el-table-column align="center" prop="unitName" label="单位名称">
        </el-table-column>
        <el-table-column align="center" prop="description" label="角色描述">
          <template slot-scope="scope">
            <span>{{ scope.row.description == null ? '—' : scope.row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="管理员身份">
          <template slot-scope="scope">
            <span>{{ scope.row.isSuperAdmin == 0 ? '普通管理员' : '超级管理员' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <div class="textBtn">
              <el-row>
                <el-col class="el" :span="6">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="echoValueForUpdate(scope.row)">编辑</span>
                </el-col>
                <el-col class="el" :span="12">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="FenPeiQuanXian(scope.row)">分配权限</span>
                </el-col>
                <el-col class="el" :span="6">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="deleteRoleById(scope.row)">删除</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <!-- 添加角色 -->
    <el-dialog :close-on-click-modal="false" width="600px" :title="AddUserPopScene === 'add' ? '添加角色' : '修改角色'"
      :visible.sync="AddUserPopShow" class="dialogStyle">
      <el-divider></el-divider>

      <el-form :model="insertForm" :rules="insertRules" ref="insertForm">

        <el-form-item label="角色名称:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input placeholder="请输入" maxlength="20" v-model="insertForm.name" autocomplete="off"
            style="width: 300px"></el-input>
        </el-form-item>

        <el-form-item label="角色类型:" :label-width="formLabelWidth" class="formItemStyle" prop="unitType">
          <el-select @change="unitTypeChange" style="width: 300px" clearable v-model="insertForm.unitType"
            placeholder="请选择">
            <el-option v-for="item, i in unitTypeData" :key="i" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="logOnUser.unitType == 'system' && (insertForm.unitType == 'company' || insertForm.unitType == 'agency')"
          label="所属单位:" :label-width="formLabelWidth" class="formItemStyle" prop="" required>
          <div class="block" style="display: flex;">
            <el-button size="medium" type="" @click="toSelectUnit">选择</el-button>
            <el-input v-model="insertForm.unitName" size="medium" style="width: 220px;margin-left: 10px;" disabled
              placeholder="请点击按钮进行选择"></el-input>
          </div>
        </el-form-item>

        <el-form-item label="角色描述:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input placeholder="请输入" maxlength="50" v-model="insertForm.description" autocomplete="off"
            style="width: 300px" type="textarea" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="是否超级管理员:" prop="isSuperAdmin" :label-width="formLabelWidth" class="formItemStyle">
          <template>
            <el-radio v-model="insertForm.isSuperAdmin" :label="0">否</el-radio>
            <el-radio v-model="insertForm.isSuperAdmin" :label="1">是</el-radio>
          </template>
        </el-form-item>

      </el-form>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="AddUserPopShow = false">取 消</el-button>
        <el-button v-if="AddUserPopScene == 'add'" type="primary" @click="goNext('insertForm')">下一步</el-button>
        <el-button v-if="AddUserPopScene == 'update'" type="primary" @click="update1('insertForm')">保存</el-button>
        <!-- <el-button v-if="insertForm.typeDisable == false" type="primary" @click="insertRoleAndCloseForm('insertForm')">确
          定</el-button>
        <el-button v-if="insertForm.typeDisable" type="primary" @click="updateRoleAndCloseForm('insertForm')">确
          定</el-button> -->
      </div>

    </el-dialog>

    <!-- 权限设置弹窗 -->
    <el-dialog :close-on-click-modal="false" title="" width="600px" :visible.sync="permissionSetShow"
      class="dialogStyle">
      <el-tabs v-model="permissionSetTab" style="margin-top: 10px;">

        <!-- 功能权限 -->
        <el-tab-pane label="功能权限" name="function">
          <div style="display: flex;padding: 10px;box-sizing: border-box;">
            <div style="font-weight: 600;width: 100px;text-align: right;">权限：</div>
            <div style="height: 250px;overflow-y: scroll;flex: 1">
              <el-tree :check-strictly="true" @check="hanleCheck" :data="permissionFunData" default-expand-all
                ref="permissionFun" node-key="id" :default-checked-keys="permissionFunDefaultChecked"
                :props="permissionFunProps" show-checkbox @check-change="permissionSetCheckChange">
              </el-tree>
            </div>
          </div>
        </el-tab-pane>


        <!-- 数据权限 -->
        <el-tab-pane label="数据权限" name="data">
          <el-input :value="`已选择${permissionDataTotal}项`" placeholder="" disabled></el-input>
          <!-- 筛选项 -->
          <div style="display: flex;justify-content: space-between;margin: 20px 0;">
            <el-input maxlength="20" style="width: 200px;" v-model="permissionDataKeyName"
              placeholder="根据社区名称搜索"></el-input>
            <el-cascader ref="permissionDataKeyRoom" v-if="permissionDataKeyRoomShow" clearable style="width: 300px;"
              v-model="permissionDataKeyRoom" :props="permissionDataKeyRoomProps"
              @change="permissionDataKeyRoomChange"></el-cascader>
            <el-button type="primary" size="mini" @click="permissionDataFilterClick">查询</el-button>
          </div>
          <!-- tree -->
          <div style="height: 250px;overflow-y: scroll;">
            <!-- 预加载模式 -->
            <!-- <el-tree  :load="permissionDataload" lazy ref="permissionData"
              node-key="label" :default-checked-keys="permissionDataDefaultChecked" :props="permissionDataProps"
              show-checkbox @check-change="permissionDataCheckChange('permissionData')">
            </el-tree> -->
            <!-- 静态数据 -->
            <el-tree ref="permissionData" default-expand-all :data="permissionDataTreeData" node-key="code"
              :default-checked-keys="permissionDataDefaultChecked" :props="permissionDataProps" show-checkbox
              @check-change="permissionDataCheckChange">
            </el-tree>
          </div>
        </el-tab-pane>

      </el-tabs>
      <el-divider></el-divider>
      <div style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="permissionSetShow = false">取 消</el-button>
        <el-button v-if="permissionSetScene == 'add'" type="primary" @click="permissionSetOk">确认</el-button>
        <el-button v-if="permissionSetScene == 'update'" type="primary" @click="update2">确认</el-button>
      </div>


    </el-dialog>

    <!-- 选择单位弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="600px" title="选择单位"
      :visible.sync="selectUnitPopShow">
      <el-divider></el-divider>
      <!-- 筛选项 -->
      <div style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-input maxlength="20" size="medium" style="width: 200px;" v-model="selectUnitPopKeyName"
          placeholder="根据单位名称搜索"></el-input>
        <el-select disabled size="medium" style="width: 262px" placeholder="请选择所属单位" v-model="selectUnitPopKeyType"
          clearable>
          <el-option v-for="item, i in unitTypeData" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-button size="medium" type="primary" @click="getSelectUnitPopData">查询</el-button>
      </div>

      <div class="popTableStyle">
        <el-table ref="selectUnitPopTable" @current-change="selectUnitPopChange" :data="selectUnitPopData"
          style="width: 100%" height="400px" highlight-current-row>
          <el-table-column align="center" prop="unitName" label="单位名称">
          </el-table-column>
          <el-table-column align="center" prop="unitType" label="单位类型" width="180">
            <template slot-scope="scope">
              {{ scope.row.unitType == 'agency' ? '机关' : scope.row.unitType
                == 'company' ? '机构' : '系统' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectUnitPopNot('selectUnitPop')">取 消</el-button>
        <el-button type="primary" @click="selectUnitPopOk('selectUnitPop')">确
          定</el-button>
      </div>

    </el-dialog>
    <!-- 选择单位弹窗结束 -->


    <!-- 分页器 -->
    <myPagination :pageNum="pageNum" :total="totalSize" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>





<script>
import axios from 'axios'
import {
  getAllMenuList
} from "../system/menu/menu";

export default {

  data() {
    return {
      // 选择单位弹窗
      selectUnitPopShow: false,//选择角色弹窗显隐
      selectUnitPopKeyName: '',
      selectUnitPopKeyType: '',
      selectUnitPopData: [],
      selectUnitPopCache: {},//暂存区


      // 权限设置弹窗
      permissionSetShow: false,
      permissionSetTab: 'function',
      permissionSetScene: 'add',
      // 权限设置弹窗 ——功能权限
      permissionFunData: [],
      permissionFunProps: {
        children: 'children',
        value: 'id',
        label: 'title',
        isLeaf: 'leaf'
      },
      permissionFunDefaultChecked: [],//功能权限的tree的默认选中
      // 权限设置弹窗 ——数据权限
      permissionDataTotal: 0,
      permissionDataKeyName: '',
      permissionDataKeyLevel: '',
      permissionDataTreeData: [
      ],
      permissionDataKeyRoom: [],
      permissionDataKeyRoomShow: false,
      permissionDataKeyRoomProps: {
        lazy: true,
        value: 'value',
        checkStrictly: true,
        label: 'label',
        lazyLoad: async (node, resolve) => {
          console.log(node, '级联懒加载');

          if (node.level == 0) {
            let res = await this.$api.system.myQueryAreaList('000000')
            if (res.code == 200) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  value: el.criCode,
                  label: el.criName
                });
              });
              resolve(arr)
            } else {
              this.$message.error(res.message)
            }
          } else if (node.level == 1) {
            let res = await this.$api.system.myQueryAreaList(node.data.value)
            if (res.code == 200) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  value: el.criCode,
                  label: el.criName
                });
              });
              resolve(arr)
            } else {
              this.$message.error(res.message)
            }
          } else if (node.level == 2) {
            let res = await this.$api.system.myQueryAreaList(node.data.value)
            if (res.code == 200) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  value: el.criCode,
                  label: el.criName
                });
              });
              resolve(arr)
            } else {
              this.$message.error(res.message)
            }
          } else if (node.level == 3) {
            let res = await this.$api.system.myQueryAreaList(node.data.value)
            if (res.code == 200) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  value: el.criCode,
                  label: el.criName,
                  leaf: true,
                });
              });
              resolve(arr)
            } else {
              this.$message.error(res.message)
            }
          } else if (node.level == 4) {
            resolve([])
          }
        }
      },
      permissionDataDefaultChecked: [],// 数据权限的tree的默认选中
      permissionDataProps: {
        children: 'children',
        value: 'code',
        label: 'name',
        isLeaf: 'leaf'
      },



      roleData: [], //用户数据
      query: {
        //左上角查询input
        roleName: "",
      },

      AddUserPopShow: false, //控制弹框开关
      formLabelWidth: "140px", //控制前面label的宽度
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      props: {
        label: 'title',
        children: 'children'
      },
      menuData: [],
      defaultCheckedKeys: [],

      // 新增角色弹窗
      AddUserPopScene: '',
      unitTypeData: [],
      insertForm: {
      },
      insertRules: {
        name: [
          {
            required: true,
            message: "用户名称不能为空",
            trigger: "blur",
          },
        ],
        unitType: [
          {
            required: true,
            message: "角色类型不能为空",
            trigger: "change",
          },
        ],
        isSuperAdmin: [
          {
            required: true,
            message: "请选择是否为超级管理员",
            trigger: "change",
          },
        ],
      },
      activeRowDetail: {},
      logOnUser: {},
    };
  },

  methods: {
    async getMenuTreeList() {
      if (this.logOnUser.unitType == 'system') {
        // 获取功能权限tree数据
        getAllMenuList().then((res) => {
          this.permissionFunData = res;
        });

      } else {
        axios({
          url: defaultUrl + '/auth/menu/getUnitSuperRoleMenuListByAccount',
          methods: 'get',
          headers: {
            account: this.logOnUser.account,
            token: this.logOnUser.token,
            unitType: this.logOnUser.unitType,
            unitId: this.logOnUser.unitId,
          },
        }).then(res => {
          if (res.data.code == 200) {
            this.permissionFunData = res.data.data
          } else {
            this.$message.error(res.data.message)
          }

        }).catch(err => {
          console.log(err, '错误')
        })
        // this.$http.get("/auth/menu/getRoleMenuListByAccount").then(res => {
        //   this.permissionFunData = res.data.data
        // });
      }
    },
    // 单位列表弹窗==============================================
    unitTypeChange() { //角色类型发生变化时，要清空选择的单位
      this.insertForm.unitName = ''
      this.insertForm.unitId = ''
    },
    async toSelectUnit() {//点击去选择单位
      this.selectUnitPopShow = true
      this.selectUnitPopKeyName = ''
      this.selectUnitPopKeyType = this.insertForm.unitType
      this.getSelectUnitPopData()
    },
    async getSelectUnitPopData() { //获取单位列表数据
      let res = await this.$api.system.myGetUnitByType({
        "name": this.selectUnitPopKeyName,
        "unitId": this.logOnUser.unitId,
        "unitType": this.selectUnitPopKeyType,
      })
      console.log(res, '选择单位的列表');
      if (res.code == 200) {
        this.selectUnitPopData = res.data
        this.$nextTick(() => {
          if (!this.insertForm.unitId) { //如果没选择就点确定，或者第一次打开，先清空预存的值
            this.selectUnitPopCache = {}
            return
          }
          this.selectUnitPopData.forEach((el, i) => {
            if (el.unitId == this.insertForm.unitId) {
              this.$refs.selectUnitPopTable.setCurrentRow(this.selectUnitPopData[i])
            }
          })
        })
      } else {
        this.$message.error(res.message)
      }
    },
    selectUnitPopNot(name) {//选择角色取消按钮
      this.selectUnitPopShow = false
    },
    selectUnitPopOk(name) { //选择角色确认按钮
      function isEmptyObject(obj) {
        return Object.keys(obj).length === 0;
      }
      if (isEmptyObject(this.selectUnitPopCache)) {
        this.$message.error('请选择单位')
        return
      }
      this.insertForm.unitId = this.selectUnitPopCache.unitId
      this.insertForm.unitName = this.selectUnitPopCache.unitName
      this.selectUnitPopShow = false
    },
    selectUnitPopChange(val) { //预选
      console.log(val);
      this.selectUnitPopCache = val
    },
    // ======================================单位列表弹窗

    // 增删改 =============================
    async echoValueForUpdate(row) {// 修改角色信息

      this.AddUserPopScene = 'update'
      let res = await this.$api.system.myGetRoleDetail(row.id)
      console.log(res, '详情信息');
      if (res.code == 200) {
        this.activeRowDetail = res.data
        this.AddUserPopShow = true
        this.$set(this.insertForm, 'name', res.data.name)
        this.$set(this.insertForm, 'isSuperAdmin', res.data.isSuperAdmin)
        this.$set(this.insertForm, 'unitType', res.data.unitType)
        this.$set(this.insertForm, 'description', res.data.description)
        this.$set(this.insertForm, 'unitId', res.data.unitId)
        this.$set(this.insertForm, 'unitName', res.data.unitName)
      } else {
        this.$message.error(res.message)
      }
      this.$nextTick(() => {
        this.$refs['insertForm'].clearValidate()
      })
    },
    async update1() {  //编辑角色基本信息
      this.$confirm('是否确认修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { rqList, id, menuList } = this.activeRowDetail  //这几个字段就用详情的，不改
        let unitId;
        switch (this.logOnUser.unitType) {
          case 'system':
            if (this.insertForm.unitType == 'system') {
              unitId = 0
            }
            if (this.insertForm.unitType == 'agency') {
              if (!this.insertForm.unitId) {
                this.$message.error('请选择所属单位')
                return
              } else {
                unitId = this.insertForm.unitId
              }
            }
            if (this.insertForm.unitType == 'company') {
              if (!this.insertForm.unitId) {
                this.$message.error('请选择所属单位')
                return
              } else {
                unitId = this.insertForm.unitId
              }
            }
            break
          case 'agency':
            unitId = this.logOnUser.unitId
            break
          case 'company':
            unitId = this.logOnUser.unitId
            break
        }
        let { description, name, unitType, isSuperAdmin } = this.insertForm
        let params = {
          rqList, id, menuList,
          description, name, unitType, unitId, isSuperAdmin
        }
        let res = await this.$api.system.myUpdateRoleInfo(params)
        console.log(res, '修改接口');
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.AddUserPopShow = false
          this.getTableList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {

      });

    },

    async FenPeiQuanXian(row) { //分配权限函数

      this.permissionSetTab = 'function' //默认先占时功能权限tab
      this.permissionSetScene = 'update' // 当前权限弹窗状态是add
      this.permissionDataKeyName = ''
      this.permissionDataKeyLevel = ''
      this.permissionDataKeyRoom = []


      this.permissionDataKeyRoomShow = false
      setTimeout(() => { //点击下一步 就是新增的时候设置权限 清空权限弹窗的数据
        this.permissionDataKeyRoomShow = true
      }, 10)

      let res = await this.$api.system.myGetRoleDetail(row.id)
      console.log(res, '详情信息');
      if (res.code == 200) {
        this.permissionSetShow = true
        this.$nextTick(() => {
          // 先清空tree所有激活项
          this.$refs.permissionFun.setCheckedKeys([])
          this.$refs.permissionData.setCheckedKeys([])
        })
        setTimeout(() => {
          this.activeRowDetail = res.data
          // 功能权限回显 赋值
          this.permissionFunDefaultChecked = res.data.menuList
          this.insertForm.menuList = res.data.menuList
          this.$set(this.insertForm, 'unitType', res.data.unitType)
          this.$set(this.insertForm, 'unitId', res.data.unitId)
          // 数据权限回显 赋值
          this.permissionDataDefaultChecked = res.data.rqList
          this.insertForm.rqList = res.data.rqList
          // 总条数回显
          this.permissionDataTotal = res.data.rqList.length
          this.getMenuTreeList() //  获取功能权限
          this.myGetListForDataPermission() //获取数据权限
        }, 10)
      } else {
        this.$message.error(res.message)
      }
    },
    hanleCheck(data, node) {
      const _this = this;
      // console.log("==================");
      // console.log(data);
      // 获取当前节点是否被选中
      const isChecked = this.$refs.permissionFun.getNode(data).checked;
      // 如果当前节点被选中，则遍历上级节点和下级子节点并选中，如果当前节点取消选中，则遍历下级节点并取消选中
      if (isChecked) {
        // 判断是否有上级节点，如果有那么遍历设置上级节点选中
        data.parentId && setParentChecked(data.parentId);
        // 判断该节点是否有下级节点，如果有那么遍历设置下级节点为选中
        data.children && setChildreChecked(data.children, true)
      } else {
        // 如果节点取消选中，则取消该节点下的子节点选中
        data.children &&
          setChildreChecked(data.children, false);
      }
      // 选中子级，默认选中它的父级
      function setParentChecked(val) {
        // 获取该id的父级node
        const parentNode = _this.$refs.permissionFun.getNode(val);
        // 如果该id的父级node存在父级id则继续遍历
        parentNode &&
          parentNode.data &&
          parentNode.data.parentId &&
          setParentChecked(parentNode.data.parentId);

        //  设置该id的节点为选中状态
        _this.$refs.permissionFun.setChecked(val, true);
      }
      function setChildreChecked(node, isChecked) {
        console.log("==============执行");
        node.forEach((item) => {
          item.children &&
            setChildreChecked(item.children, isChecked);
          _this.$refs.permissionFun.setChecked(item.id, isChecked);
        });
      }
    },

    async update2() { //分配权限修改
      this.$confirm('是否确认修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

        // 在获取一次功能权限的所有选中项
        let b = this.$refs['permissionFun'].getCheckedNodes()//全选状态下，用来默认激活使用 permissionFun

        this.insertForm.menuList = []
        b.forEach(el => {
          this.insertForm.menuList.push(el.id)
        })


        let { name, id, description, unitType, unitId,isSuperAdmin } = this.activeRowDetail //这几个字段就用详情的，不改
        let { rqList, menuList, } = this.insertForm
        let params = {
          name, id, description, unitType, unitId, rqList, menuList,isSuperAdmin
        }

        let res = await this.$api.system.myUpdateRoleInfo(params)
        console.log(res, '修改接口');
        if (res.code == 200) {
          // location.reload();
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.permissionSetShow = false
          this.getTableList()
          this.$eventBus.$emit('Refresh')
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {

      });

    },
    deleteRoleById(row) {
      this.$confirm("确认删除该角色吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        let res = await this.$api.system.myDeleteRoleOnLogic(row.id)
        if (res.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getTableList();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      }).catch(() => {

        return;
      });
    },
    // ================================增删改





    //弹出增加角色弹窗
    openForm(type) {
      this.AddUserPopShow = true

      this.AddUserPopScene = 'add'
      this.$set(this.insertForm, 'isSuperAdmin', '')
      this.$set(this.insertForm, 'name', '')
      this.$set(this.insertForm, 'unitType', '')
      this.$set(this.insertForm, 'description', '')


      this.$nextTick(() => {
        this.$refs['insertForm'].clearValidate()
      })
    },
    goNext(name) { //点击新增用户的下一步按钮
      this.$refs[name].validate((valid) => {
        if (valid) {
          switch (this.logOnUser.unitType) {
            case 'system':
              if (this.insertForm.unitType == 'system') {
              }
              if (this.insertForm.unitType == 'agency') {
                if (!this.insertForm.unitId) {
                  this.$message.error('请选择所属单位')
                  return
                }
              }
              if (this.insertForm.unitType == 'company') {
                if (!this.insertForm.unitId) {
                  this.$message.error('请选择所属单位')
                  return
                }
              }
              break
            case 'agency':
              break
            case 'company':
              break
          }

          this.AddUserPopShow = false
          this.permissionSetShow = true
          this.permissionSetTab = 'function' //默认先占时功能权限tab
          this.permissionSetScene = 'add' // 当前权限弹窗状态是add
          this.permissionDataKeyRoomShow = false
          this.getMenuTreeList() //  获取功能权限
          this.myGetListForDataPermission() //获取数据权限
          setTimeout(() => { //点击下一步 就是新增的时候设置权限 清空权限弹窗的数据
            this.permissionDataKeyRoomShow = true
            this.permissionDataTotal = 0
            this.permissionDataKeyName = ''
            this.permissionDataKeyLevel = ''
            this.permissionDataKeyRoom = []
            this.$refs.permissionFun.setCheckedKeys([])
            this.$refs.permissionData.setCheckedKeys([])
            this.$set(this.insertForm, 'menuList', [])
            this.$set(this.insertForm, 'rqList', [])
          }, 10)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 功能权限==============================
    permissionSetCheckChange(a1, a2, a3) {  // 功能权限tree选中项发生变化时
      // this.$refs['permissionFun'].setCheckedKeys([112]);
      let b = this.$refs['permissionFun'].getCheckedNodes()//全选状态下，用来默认激活使用 permissionFun
      console.log(a1, a2, a3, 'qwdca')
      // let maxLevel = 0
      // b.forEach(el => {
      //   if (maxLevel < el.level) {
      //     maxLevel = el.level
      //   }
      // })
      this.insertForm.menuList = []
      b.forEach(el => {
        // if (el.level == maxLevel) {
        //   this.insertForm.menuList.push(el.id)
        // }
        this.insertForm.menuList.push(el.id)
      })
    },
    permissionSetOk() { //权限弹窗 确认按钮
      this.$confirm('请您仔细检查再提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let unitId;
        switch (this.logOnUser.unitType) {
          case 'system':
            if (this.insertForm.unitType == 'system') {
              unitId = 0
            }
            if (this.insertForm.unitType == 'agency') {
              unitId = this.insertForm.unitId
            }
            if (this.insertForm.unitType == 'company') {
              unitId = this.insertForm.unitId
            }
            break
          case 'agency':
            unitId = this.logOnUser.unitId
            break
          case 'company':
            unitId = this.logOnUser.unitId
            break
        }
        let { description, menuList, name, rqList, unitType, isSuperAdmin } = this.insertForm
        let params = { description, menuList, name, rqList, unitId, unitType, isSuperAdmin }
        let res = await this.$api.system.myInsertRole(params)
        console.log(res, '新增接口');
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '新增成功!'
          });
          this.permissionSetShow = false
          this.getTableList()
        } else {
          this.$message.error(res.message)
        }

      }).catch(() => {

      });
    },

    //数据权限 =========================================================
    permissionDataKeyRoomChange(val) { //数据权限的下拉框筛选事件
      console.log(val, '数据权限的下拉框筛选事件');
      if (val.length == 0) {
        this.permissionDataKeyLevel = 0
        this.permissionDataKeyRoom = []
        this.myGetListForDataPermission()
        return
      }
      this.$nextTick(() => {

        const checkedNodes = this.$refs['permissionDataKeyRoom'].getCheckedNodes()
        const pathLabels = checkedNodes[0].level
        this.permissionDataKeyLevel = pathLabels
        this.myGetListForDataPermission()
        const dom = document.getElementsByClassName("el-radio is-checked");
        let radioDom = dom[dom.length - 1];
        const brother = radioDom.nextElementSibling;
        brother.click();
      });
    },
    async permissionDataload(node, resolve) { //数据权限的tree预加载模式
      console.log(node, '数据权限的tree预加载模式');
      if (node.level == 0) {
        let res = await this.$api.system.myQueryAreaList('000000')
        if (res.code == 200) {
          let arr = []
          res.data.forEach(el => {
            arr.push({
              value: el.criCode,
              label: el.criName
            });
          });
          resolve(arr)
        } else {
          this.$message.error(res.message)
        }
      } else if (node.level == 1) {
        let res = await this.$api.system.myQueryAreaList(node.data.value)
        if (res.code == 200) {
          let arr = []
          res.data.forEach(el => {
            arr.push({
              value: el.criCode,
              label: el.criName
            });
          });
          resolve(arr)
        } else {
          this.$message.error(res.message)
        }
      } else if (node.level == 2) {
        let res = await this.$api.system.myQueryAreaList(node.data.value)
        if (res.code == 200) {
          let arr = []
          res.data.forEach(el => {
            arr.push({
              value: el.criCode,
              label: el.criName
            });
          });
          resolve(arr)
        } else {
          this.$message.error(res.message)
        }
      } else if (node.level == 3) {
        let res = await this.$api.system.myQueryAreaList(node.data.value)
        if (res.code == 200) {
          let arr = []
          res.data.forEach(el => {
            arr.push({
              value: el.criCode,
              label: el.criName,
            });
          });
          resolve(arr)
        } else {
          this.$message.error(res.message)
        }
      } else if (node.level == 4) {
        resolve([])
      }

    },
    permissionDataCheckChange(node, state) {  // 数据权限tree选中项发生变化时
      console.log(node, state, 'albb')
      if (node.level == 5) {
        if (state) { //如果是新增
          // 检查 a 数组中是否没有与 itemB.code 相等的元素  
          let abc = this.insertForm.rqList.some(el => {
            return el == node.code
          })
          if (!abc) {
            this.insertForm.rqList.push(node.code)
          }
        } else {//如果是去除
          this.insertForm.rqList.forEach((el, i) => {
            if (el == node.code) {
              this.insertForm.rqList.splice(i, 1)
            }
          })
        }
        console.log(node, state, this.insertForm.rqList, 'qwdqwd');
      }


      // 遍历选中状态数组，选择最后一级的数量
      this.permissionDataTotal = this.insertForm.rqList.length
    },
    permissionDataFilterClick() { //根据关键字查询数据权限
      this.myGetListForDataPermission()
    },
    async myGetListForDataPermission() {
      if (this.permissionDataKeyRoom.length == 0) {
        this.permissionDataKeyRoom = ['']
      }
      if (this.logOnUser.unitType == 'system') {
        // 获取数据权限数据
        let res = await this.$api.system.myGetListForDataPermission({
          name: this.permissionDataKeyName,
          level: this.permissionDataKeyLevel,
          code: this.permissionDataKeyRoom[this.permissionDataKeyRoom.length - 1],
        })
        if (res.code == 200) {
          this.permissionDataTreeData = res.data
        } else {
          this.$message.error(res.message)
        }
      } else {
        let res = await this.$api.axios.post('/business/residentialQuarters/getListForDataPermissionSuper', {
          "unitType": this.logOnUser.unitType, //必填 单位类型 机关:agency 机构:company
          "unitId": this.logOnUser.unitId //对应的机关机构id
        })
        if (res) {
          this.permissionDataTreeData = res.data
        }
      }



    },

    // =================================================数据权限






    // 列表 ===========================================
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.getTableList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageNum = 1
      this.pageSize = e
      this.getTableList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getTableList()
    },
    reset() {
      this.pageNum = 1
      this.$set(this.query, 'roleName', '')
      this.$set(this.query, 'roleType', '')
      this.getTableList()
    },
    //按条件查询菜单列表
    async getTableList() {

      let res = await this.$api.system.myRoleGetRoleList({
        "name": this.query.roleName, //角色名称
        "unitType": this.query.roleType, //机关：agency  机构：company  系统：system
        "unitId": this.logOnUser.unitId, //系统传0
        "pageNum": this.pageNum,
        "pageSize": this.pageSize,
        isSuperAdmin: this.query.isSuperAdmin

        // query.roleType
      })
      console.log(res, '列表数据');
      if (res.code == 200) {
        if (res.data.list.length == 0 && this.pageNum != 1) {
          this.pageNum = 1
          this.getTableList()
          return
        }
        this.roleData = res.data.list;
        this.totalSize = res.data.total;
      } else {
        this.$message.error(res.message)
      }

    },
    // =============================================列表

  },

  async activated() {

    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))

    switch (this.logOnUser.unitType) {
      case 'system':
        this.unitTypeData = [
          { label: '系统管理员', value: 'system' },
          { label: '机关管理员', value: 'agency' },
          { label: '机构管理员', value: 'company' },
        ]
        this.$set(this.query, 'roleType', '')
        break
      case 'agency':
        this.unitTypeData = [
          { label: '机关管理员', value: 'agency' },
        ]
        this.$set(this.query, 'roleType', 'agency')
        break
      case 'company':
        this.unitTypeData = [
          { label: '机构管理员', value: 'company' },
        ]
        this.$set(this.query, 'roleType', 'company')
        break
    }

    this.$set(this.query, 'roleName', '')
    this.$set(this.query, 'isSuperAdmin', '2')
    this.getTableList()
  },
};
</script>
<style scoped lang="less">
.popTableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }
  }
}

.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {

      // border-left: 1px solid #aaa;
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}



.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}



.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.Top {
  position: relative;

  .operation {
    position: absolute;
    left: 15px;
    top: 68px;
  }
}




.formItemStyle {
  margin-bottom: 22px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}
</style>